#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'ben'
__mtime__ = '16-4-14'
"""

import sys
import logging
import tornado.web
import tornado.ioloop
import json
from baseapi.jsonlib import MyJsonEncoder
from company_orm import CCompanyORM
from baseapi.regex_func import filter_keyword

logger = logging.getLogger('info')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('/home/log/base_info_tornado.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)

table_names = ['wy_cmp_aptitude_info', 'wy_cmp_branch_info', 'wy_cmp_evolution_log_info',
               'wy_cmp_external_guarantee_info', 'wy_cmp_main_manager_info', 'wy_cmp_ownership_structure_info',
               'wy_cmp_penalty_info', 'wy_company_base_info']

action_tbname = {
    '/like': 'wy_company_base_info',
    '/exact': 'wy_company_base_info',
    '/fuzzy': 'wy_company_base_info',
    '/baseinfo': 'wy_company_base_info',
    '/aptitude': 'wy_cmp_aptitude_info',
    '/evolution': 'wy_cmp_evolution_log_info',
    '/manager': 'wy_cmp_main_manager_info',
    '/ownership': 'wy_cmp_ownership_structure_info',
    '/guarantee': 'wy_cmp_external_guarantee_info',
    '/penalty': 'wy_cmp_penalty_info',
    '/all': table_names
}


class MainHandler(tornado.web.RequestHandler):

    def __init__(self,application,request,**kwargs):
        super(MainHandler, self).__init__(application=application, request=request, **kwargs)
        self.logs = []

    def get(self):
        ret = {}
        message = ''
        status = 'false'
        data = []
        try:
            keyword,cmp_name = '',''

            uri = self.request.path
            if not action_tbname.has_key(uri):
                raise Exception('not support request')

            if uri == '/like' or uri == '/fuzzy':
                keyword = self.get_argument('keyword')
                if not keyword:
                    raise Exception('keyword is null')

                msg = __file__ + '|' + str(sys._getframe().f_lineno) + '|' + '|keyword|' + keyword
                self.logs.append(msg)

                keyword = filter_keyword(keyword)
                if not keyword:
                    raise Exception('keyword is not valid')

                msg = __file__ + '|' + str(sys._getframe().f_lineno) + '|' + '|keyword-filter|' + keyword
                self.logs.append(msg)
            else:
                cmp_name = self.get_argument('cmp_name')
                if not cmp_name:
                    raise Exception('cmp_name is null')

                msg = __file__ + '|' + str(sys._getframe().f_lineno) + '|' + '|cmp_name|' + cmp_name
                self.logs.append(msg)

                cmp_name = filter_keyword(cmp_name)
                if not cmp_name:
                    raise Exception('cmp_name is not valid')

                msg = __file__ + '|' + str(sys._getframe().f_lineno) + '|' + '|cmp_name-filter|' + cmp_name
                self.logs.append(msg)

            display_null = self.get_argument('display_null', True)
            if display_null == '0':
                display_null = False
            else:
                display_null = True

            cmp_orm = CCompanyORM()

            if uri == '/all':
                process_res = cmp_orm.get_all_info(col_value=cmp_name, display_null=display_null)
            elif uri == '/like' or uri == '/fuzzy':
                process_res = cmp_orm.get_fuzzy_name(keyword=keyword)
            else:
                tb_name = action_tbname.get(uri)
                process_res = cmp_orm.get_data(col_value=cmp_name, tb_name=tb_name, display_null=display_null)

            if process_res is None:
                status = 'false'
                message = 'fetch record failed'
            else:
                status = 'true'
                message = 'success'
                data = process_res

        except Exception as e:
            msg = __file__ + '|' + str(sys._getframe().f_lineno) + '|' + '|error|' + e.message
            self.logs.append(msg)
            message = msg
            status = 'false'
        finally:
            ret['status'] = status
            ret['msg'] = message
            ret['data'] = data

            res = json.dumps(ret, cls=MyJsonEncoder)
            msg = __file__ + '|' + str(sys._getframe().f_lineno) + '|' + '|result|' + res
            self.logs.append(msg)

            self.set_header("Content-Type", "application/json;charset=utf-8")
            self.write(res)

            logger.log(logging.INFO, __file__ + '|' + str(
                sys._getframe().f_lineno) + '|---------------------------------------------------------------------------------')

            for i in self.logs:
                logger.log(logging.INFO, i)

            logger.log(logging.INFO, __file__ + '|' + str(
                sys._getframe().f_lineno) + '|---------------------------------------------------------------------------------')

        return


application = tornado.web.Application([
    (r"/like", MainHandler),
    (r"/exact", MainHandler),
    (r"/fuzzy",MainHandler),
    (r"/baseinfo",MainHandler),
    (r"/evolution",MainHandler),
    (r"/ownership",MainHandler),
    (r"/manager", MainHandler),
    (r"/penalty", MainHandler),
    (r"/aptitude", MainHandler),
    (r"/guarantee", MainHandler),
    (r"/all", MainHandler),
])

if __name__ == "__main__":
    # port = 8001
    port = int(sys.argv[1])
    application.listen(port=port)
    tornado.ioloop.IOLoop.instance().start()